package com.wutong.common_server.exception;


import com.wutong.common_server.result.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;


/**
 * 全局异常处理
 *
 * @author lhq
 * @date 2019/9/18
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
    @ResponseBody
    @ExceptionHandler(MyException.class)
    public CommonResult handleMyException(MyException myException) {
//        StringWriter sw = new StringWriter();
//        myException.printStackTrace(new PrintWriter(sw, true));
    	LOGGER.info(">>>>>>>>>>>>>>>>handleMyException>>>>>>>>>>>>Message:{}" , myException.getMessage());
        return new CommonResult(myException.getCode(),myException.getMessage());
    }
    
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public CommonResult handleException(Exception exception) {
//        LOGGER.info(">>>>>>>>>>>>>>>>handleException>>>>>>>>>>>>StackTrace:{}" , exception.getMessage() , exception.getCause().toString(), exception.getStackTrace().toString());
        StringWriter sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw, true));
        LOGGER.info(">>>>>>>>>>>>>>>>handleException>>>>>>>>>>>>Message:{}"  , sw.toString());
    	if( exception instanceof MyException) {
			return new CommonResult("1",exception.getMessage());
		}
        return new CommonResult("1","系统错误，请重试!");
    }
}
